import React, {Component} from 'react';
import './List.css'
import Header from '../Header'
import List from '../List'
import Footer from '../Footer'

export default class Index extends Component {

  state = {todo: []}

  componentDidMount() {
    let todo = [];
    todo.push({name: '数据一', id: 1, checked: false})
    todo.push({name: '数据二', id: 2, checked: false})
    todo.push({name: '数据三', id: 3, checked: false})
    this.setState({todo: todo})
  }

  addTodo = (todoObj) => {
    const {todo} = this.state;
    this.setState({todo: [todoObj, ...todo]})
  }

  updateTodo = (id, checked) => {
    const {todo} = this.state;
    const newTodo = todo.map((item, index) => {
      if (item.id === id) {
        item.checked = checked
      }
      return item;
    });
    this.setState({todo: newTodo})
  }

  deleteTodo = (id) => {
    const {todo} = this.state;
    const newTodo = todo.filter((item) => {
      return item.id !== id;
    })
    this.setState({todo: newTodo})
  }

  handleCheckAll = (checked) => {
    const {todo} = this.state;
    const newTodo = todo.map((item, index) => {
      item.checked = checked
      return item;
    });
    this.setState({todo: newTodo})
  }

  handleClearAllDone = () => {
    this.setState({todo: []})
  }

  render() {
    const {todo} = this.state;
    return (
        <div className="todo-container">
          <div className="todo-wrap">
            <Header addTodo={this.addTodo}/>
            <List updateTodo={this.updateTodo} deleteTodo={this.deleteTodo}
                  todo={todo}/>
            <Footer handleCheckAll={this.handleCheckAll}
                    handleClearAllDone={this.handleClearAllDone}
                    todo={todo}/>
          </div>
        </div>
    )
  }
}
